package com.javacv.plus.extensions.audio.steps;

import com.javacv.plus.core.processor.ProcessorContext;
import com.javacv.plus.core.processor.ProcessorStep;
import com.javacv.plus.extensions.audio.AudioProcessor;
import com.javacv.plus.extensions.audio.AudioResult;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;

/**
 * 速度调整步骤
 */
@Slf4j
public class SpeedStep implements ProcessorStep<AudioProcessor, AudioResult> {
    private final double factor;

    public SpeedStep(double factor) {
        this.factor = factor;
    }

    @Override
    public AudioResult execute(AudioProcessor processor, ProcessorContext context) throws Exception {
        log.info("Adjusting speed with factor: {}", factor);

        FFmpegFrameGrabber grabber = (FFmpegFrameGrabber) context.getAttribute("grabber");
        try (FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(
                "temp_speed.mp3",
                grabber.getAudioChannels(),
                (int) (grabber.getSampleRate() * factor)
        )) {
            recorder.setFormat(grabber.getFormat());
            recorder.setAudioBitrate(grabber.getAudioBitrate());
            recorder.setAudioChannels(grabber.getAudioChannels());
            recorder.setSampleRate((int) (grabber.getSampleRate() * factor));
            recorder.start();

            // 处理音频帧
            while (true) {
                Frame frame = grabber.grab();
                if (frame == null) {
                    break;
                }

                recorder.record(frame);
            }
        }

        // 更新上下文
        context.setAttribute("grabber", new FFmpegFrameGrabber("temp_speed.mp3"));
        log.info("Speed adjustment completed");
        return null;
    }

    @Override
    public String getStepName() {
        return "Speed";
    }
} 